package com.yourwork.service.imp;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yourwork.dao.ClienteleDao;
import com.yourwork.model.Clientele;
import com.yourwork.service.ClienteleService;
@Service(value="customerService")
public class ClienteleServiceImp implements ClienteleService {
	@Autowired
	@Qualifier(value="clienteleDao")
	private ClienteleDao clienteleDao;

	public Page<Clientele> queryCustomer(int page, int size) {
		// TODO Auto-generated method stub
		try {
			int count;
			count = clienteleDao.countCustomer();
			//判断page的值
			if(page<0){page = 0;}
			if(page<=(count/size)&&count%size!=0){page=page+0;}
				else{if(count%size==0){page=count/size-1;}
				else{page = count/size;}}
			Pageable pageable = new PageRequest(page,size,Sort.Direction.ASC,"id");
			return clienteleDao.queryCustomer(pageable);
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
	}
	//按userName查询
	public Clientele quserCUserName(String userName) {
		// TODO Auto-generated method stub
		try {
			Clientele customer=clienteleDao.quserCUserName(userName);
			return customer;
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}

	}
	//修改用户信息
	public String updateCustomer(Clientele customer) {
		// TODO Auto-generated method stub
		try {
			String username = customer.getUserName();
			if(customer.getId()!=0){
			Clientele c = clienteleDao.quserCUserName(username);
			customer.setBalance(c.getBalance());
			customer.setDiscount(c.getDiscount());
			clienteleDao.updateCustomer(customer);
			return "修改成功";}else{	
				return insertCustomer(customer);
			}
		} catch (Exception e) {
			// TODO: handle exception
			return "修改失败";
		}

	}
	//添加新的用户
	public String insertCustomer(Clientele customer) {
		// TODO Auto-generated method stub
		try {
			clienteleDao.insertCustomer(customer);
			 return "添加成功";
		} catch (Exception e) {
			// TODO: handle exception
			return "添加失败,请检查是否用户名已存在";
		}

	}
	//获取用户总数
	public int countCustomer() {
		// TODO Auto-generated method stub
		return clienteleDao.countCustomer();
	}
	public int queryMaxPage(int page, int size) {
		// TODO Auto-generated method stub
		int count;
		count = clienteleDao.countCustomer();
		if(count%size==0){page=count/size-1;}
		else{page = count/size;}
		return page;
	}
}
